window.onload = function() {
    const $ = name => document.querySelector(name);
    var teacherlogo = document.getElementById('teachercentre');
    var un = window.localStorage.getItem('username');
    var role6 = window.localStorage.getItem('role');
    var dropbtn = $('.dropdown');
    if (role6 == 'teacher') {
        teacherlogo.style.display = 'block';
    }
    document.getElementById('userinfo').innerHTML = '用户名' + '&nbsp' + un;
    document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
    //关于cookie注销的函数
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }
    //退出登录，返回主页
    function Outlogin() {
        window.localStorage.removeItem("token");
        window.localStorage.removeItem('role');
        window.localStorage.removeItem('id');
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
        Outlogin();
    })
    var token1 = window.localStorage.getItem('token');
    var rlogo = document.getElementById('rlogo');
    var userinfo = document.getElementById('userinfo');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    // personBusi();
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        rlogo.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    //window.location.href = 'index1.html';
                } else if ((response.data.code == 1 && (cookie.name != '' && cookie.pass != '')) || (response.data.code == 1 && (cookie.name == '' && cookie.pass == ''))) {
                    console.log('登录状态');
                    rlogo.style.display = 'block'
                    userinfo.style.display = 'block';
                }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    personBusi();
                    console.log(response.data);
                    var res = response.data.data;
                    //使用loackstorge保存token，方便以后需要的时候用
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.avatar) {
                        document.querySelector(".pic img").src = res.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                })
        } else {
            console.log('cookie已注销');
            window.location.href = "index1.html";
        }
    }
    //封装每隔五分钟发送请求的函数
    function personBusi() {
        var cookie = JSON.parse(getCookie("init"));
        setTimeout(personBusi, 1000 * 60 * 5); //这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟 
        axios({
                url: "/login",
                method: "post",
                data: {
                    "username": cookie.name,
                    "password": cookie.pass,
                }
            })
            .then(response => {
                if (response.data.code == 1) {
                    var res1 = response.data.data;
                    console.log('刷新token');
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res1.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res1.username;
                    if (res1.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res1.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res1.avatar) {
                        document.querySelector(".pic img").src = res1.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                }
            })

    }

    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                console.log('token有效');
                var id3 = window.localStorage.getItem('username');
                var role3 = window.localStorage.getItem('role');
                userinfo.style.display = 'block';
                dropbtn.style.display = 'inline-block';
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                rlogo.style.display = 'block';
                if (window.localStorage.getItem('avatar')) {
                    document.querySelector(".pic img").src = window.localStorage.getItem('avatar');
                } else {
                    document.querySelector('#rlogo img').src = "img/register.png";
                }
            } else {
                console.log('error');
                // window.location.href = "index1.html";
                // window.location.assign("/易动考核/拉勾教育/Homepage/index1.html");
            }

        }).catch(err => {

        })
    }

    function Ifbuy() {
        axios({
            method: 'post',
            url: '/course/hasBuyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.msg == '已经购买了该课程') {
                window.location.href = '../course-details/course-details-three.html';
            } else {
                window.location.assign('../course-details/course-details-two.html');
                console.log('1');
            }
        })
    }
    //搜索功能模块
    var search_input = $('.search-input');
    var search_content = $('.search-content');
    var search_box = $('.search');
    search_input.addEventListener('input', function() {
        var value = this.value.replace(/\s/g, '')
        if (value != '') {
            search(value);
        } else {
            clearTimeout(timer);
            $('.search-content').style.display = 'none';
            search_content.innerHTML = '';
        }
    })
    search_input.addEventListener('focus', function() {
        this.style.color = '#333'
    })
    search_input.addEventListener('blur', function() {
        this.style.color = '#999'
        setTimeout(() => {
            search_input.value = '';
        }, 1000);
    })
    search_box.addEventListener('click', function(e) {
        e.stopPropagation()
        var value = search_input.value.replace(/\s/g, '')
        if (value != '') {
            search_content.style.height = '320px';
            $('.search-content').style.display = 'block';
        }
    })
    document.addEventListener('click', function() {
        search_content.style.display = 'none';
    })
    var to_search = $('.to_search');
    to_search.addEventListener('click', function() {
        var value = search_input.value.replace(/\s/g, '');
        if (value != '') {
            window.localStorage.title = value;
            window.location.href = '../Searchcourse/searchcourse.html';
        }
    })
    window.addEventListener('keyup', function(e) {
            if (e.keyCode == 13 && search_input.value != '' && search_input == document.activeElement) {
                to_search.click()
            }
        })
        //利用防抖函数优化搜索课程功能
    var timer = null

    function search(value) {
        clearTimeout(timer)
        timer = setTimeout(function() {
            axios({
                url: '/course/search',
                params: {
                    title: value
                }
            }).then(response => {
                if (response.data.msg == '查找成功') {
                    var data = response.data.data
                    var str = ''
                    for (var k in data) {
                        str +=
                            `<li courseid="` + data[k].id + `">
                       <img src="` + data[k].image + `" alt="">
                       <div class="course-info">
                           <h2 class="course-title">` + data[k].title + `</h2>
                           <div class="teacher-info">
                               <span class="teacher-name">` + data[k].teacherName + `</span>
                               <span class="teacher-work">` + data[k].teacherTitle + `</span>
                           </div>
                       </div>
                   </li>`
                    }
                    search_content.innerHTML = str;
                    var course_titles = search_content.querySelectorAll('.course-title');
                    var course_titles_len = course_titles.length;
                    var teacher_names = document.querySelectorAll('.teacher-name');
                    var teacher_works = document.querySelectorAll('.teacher-work');
                    var reg = new RegExp(value, "g");
                    for (var i = 0; i < course_titles_len; i++) {
                        course_titles[i].innerHTML = course_titles[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_names[i].innerHTML = teacher_names[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_works[i].innerHTML = teacher_works[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                    }
                    $('.search-content').style.display = 'block';
                }
                console.log(response.data);
                var li1 = document.querySelectorAll('li');
                for (let t = 0; t < li1.length; t++) {
                    li1[t].addEventListener('click', function() {
                        window.localStorage.setItem('courseid', li1[t].getAttribute('courseid'));
                        Ifbuy();
                    })
                }
            }).catch(err => {
                console.log(err);
            })
            console.log(value)
        }, 800)
    }
    var searchresult = $('.showresult');
    //教师添加新课程
    var title_input = $('.title_input');
    var price_input = $('.price_input');
    var teacher_input = $('.teacher_input');
    var oldprice_input = $('.oldprice_input');
    var classid_box = document.querySelectorAll('.checkopt');
    var brief_input = $('.brief_input');
    var teabrief_input = $('.teacherbrief_input');
    var post_btn = $('.post_btn');
    var user_id = window.localStorage.getItem('id');
    var remind = $('.remind');

    //封装一个添加课程函数
    function Addcourse(class_Id) {
        axios({
            method: 'post',
            url: '/course/addCourse',
            data: {
                user_id: user_id,
                title: $('.title_input').value,
                price: $('.price_input').value,
                teacherName: $('.teacher_input').value,
                classifyIds: class_Id,
                originalPrice: $('.oldprice_input').value,
                teacherTitle: $('.teacherbrief_input').value,
                brief: $('.brief_input').value
            }
        }).then(res => {
            if (res.data.code == 1) {
                console.log(res.data);
                // remind.Classname = ''
                remind.innerHTML = '发布成功';
                successtip();
                $('.aftertips').innerHTML = res.data.msg;
                setTimeout(() => {
                    remind.innerHTML = '';
                }, 1500);
            } else if (res.data.msg == '缺少参数') {
                console.log(res.data);
                remind.innerHTML = '信息不能留空！！';
                errtip();
                $('.aftertips').innerHTML = res.data.msg;
                setTimeout(() => {
                    remind.innerHTML = '';
                }, 1500);
            }
        }).catch(error => {
            console.log(error);
        });
    }
    post_btn.addEventListener('click', function() {
            for (let i = 0; i < classid_box.length; i++) {
                if (classid_box[i].checked) {
                    var class_Id1 = i + 1;
                }
            }
            Addcourse(class_Id1 + '')
        })
        //清空所填课程信息
    var clear = $('.clear_btn');
    clear.onclick = function() {
            title_input.value = '';
            price_input.value = '';
            teacher_input.value = '';
            oldprice_input.value = '';
            teabrief_input.value = '';
            brief_input.value = '';
            for (let i = 0; i < classid_box.length; i++) {
                classid_box[i].checked = "";
            }
        }
        //查看已上传课程
    var item2 = $('#mycourse');
    var demospace = $('.course-ul');
    var editspace = $('.editdetail');
    item2.addEventListener('click', function() {
        changepage.style.height = "0.001px";
        changepage.style.visibility = 'hidden';
        Getmycourse();
    })
    var item3 = $('#edititem');
    item3.addEventListener('click', function() {

        Getmycourse();
    })

    function Getmycourse() {
        axios({
            method: 'get',
            url: '/course/getMyCourse',
            params: {
                user_id: user_id,
            }
        }).then(response => {
            let res = response.data.data;
            console.log(res);
            appendbuycourse(res, demospace);
            // editdetail1();
            appendbriefcourse(res, editspace);
        }).catch(err => {
            console.log('获取失败，网络错误');
            console.log(err.data);
        })
    }
    //封装添加课程函数
    function appendbuycourse(res, demo) {
        demo.innerHTML = '';
        for (let i = 0; i < res.length; i++) {
            let li = document.createElement("li");
            li.className = "course-li";
            li.setAttribute('courseid', res[i].id)
                // console.log(str1);
            li.innerHTML = `
            <img src="${res[i].image}" alt="">
            <div class="_main">
                <div class="_title text-overflow">${res[i].title}</div>
                <p class="_brief text-overflow">${res[i].brief}</p>
                <p class="_teacher">${res[i].teacherName}</p>
                <div class="_foot"> <span class="_price">¥${res[i].price}</span><span class="_oldprice">¥${res[i].originalPrice}</span> </div>
                <span>${res[i].pruchasedCount}</span>
            </div>
            <div class="btnlist1">
                <div class="btn">修改课程</div>
                <div class="btn1">删除课程</div>
            </div>`;
            demo.appendChild(li);
        }
        Deletecourse(res, demo);
        Changecourse(res);
    }

    function appendbriefcourse(res, demo) {
        demo.innerHTML = '';
        for (let i = 0; i < res.length; i++) {
            let li = document.createElement("li");
            li.className = "course-li";
            li.setAttribute('courseid', res[i].id);
            // console.log(str1);
            li.innerHTML = `
            <img src="${res[i].image}" alt="">
            <div class="_main1">
                <div class="brieftitle text-overflow">${res[i].title}</div>
                <p class="briefteacher">讲师:${res[i].teacherName}&nbspid:${res[i].id}</p>
                <p class="smallbrief text-overflow1">内容简述:${res[i].brief}</p>
            </div>
            <div class="btnlist3">
                <div class="editbtn">编辑详细信息</div>
                <div class="editbtn1">管理该课程</div>
            </div>`;
            demo.appendChild(li);
        }
        editdetail(res);
        editmodule();
    }
    //删除已发课程
    //封装删除课程的函数
    function Deletepost(courseId) {
        axios({
            method: 'get',
            url: '/course/deleteMyCourse',
            params: {
                id: courseId
            }
        }).then(response => {
            let res = response.data;
            console.log(res);
        }).catch(err => {
            console.log('获取失败，网络错误');
        })
    }
    //删除已上传课程
    function Deletecourse(res, demo) {
        var btn1 = document.querySelectorAll(".btn1");
        var li = document.querySelectorAll(".course-li");
        for (let o = 0; o < btn1.length; o++) {
            btn1[o].onclick = function() {
                Deletepost(res[o].id);
                demo.removeChild(li[o]);
                $('.aftertips').innerHTML = '删除成功';
                successtip();
            }
        }
    }
    var changeid = '';
    var changepage = $('.editcourse');
    var detailpage = $('.editcourse1');
    var detailpage1 = $('.editcourse2');
    var classifyId = '';
    var checka = document.querySelectorAll('.check_box');

    function getChangeInfo(courseid) {
        return new Promise((resolve, reject) => {
            axios({
                url: '/course/getMyCourse',
                params: {
                    user_id: window.localStorage.getItem('id')
                }
            }).then(response => {
                console.log(response.data);
                if (response.data.code == 1) {
                    let data = response.data.data
                    for (var k in data) {
                        if (data[k].id == courseid) {
                            $('.add-title').value = data[k].title;
                            $('.add-courseNowPrice').value = data[k].price;
                            $('.add-teacherName').value = data[k].teacherName;
                            $('.add-courseOriginPrice').value = data[k].originalPrice;
                            $('.add-teacherBrief').value = data[k].teacherTitle;
                            $('.course-brief').value = data[k].brief;
                            console.log(data[k].classifyIds);
                            changeid = data[k].id;
                            classifyId = data[k].classifyIds.replace('[', '').replace(']', '').split(',')[1] - 0
                            checka[classifyId - 1].checked = true;
                            $('.publish-course').innerHTML = '确认修改';
                            $('.publish-cancel').innerHTML = '取消修改';

                        }
                    }
                } else {
                    $('.publish-course').innerHTML = '获取失败！'
                }
                resolve(response)
            }).catch(err => {
                console.log(err.data);
            })
        })
    }
    var changebtn = $('.publish-course');
    var cancelbtn = $('.publish-cancel');
    var cancelbtn1 = $('.canceleditbtn');
    var cancelbtn2 = $('.save-edit1');

    function detailmove() {
        detailpage.style.visibility = 'hidden';
        detailpage.style.height = "0.001px";
        setTimeout(() => {
            detailpage.style.display = 'none';
            cleardetail();
        }, 1000)
    }

    function detailmove2() {
        detailpage1.style.visibility = 'hidden';
        detailpage1.style.height = "0.001px";
        setTimeout(() => {
            detailpage1.style.display = 'none';
        }, 1000)
    }
    cancelbtn1.addEventListener('click', function() {
        detailmove();
    })
    cancelbtn2.addEventListener('click', function() {
        detailmove2();
    })
    cancelbtn.addEventListener('click', function() {
        changepage.style.visibility = 'hidden';
        changepage.style.height = "0.001px";
    })
    changebtn.addEventListener('click', function() {
        // console.log(classifyId);
        for (let i = 0; i < checkb.length; i++) {
            if (checkb[i].checked) {
                var class_Id2 = i + 1;
            }
        }
        console.log(class_Id2);
        changeBaseCourse(changeid, class_Id2 + '');
        changepage.style.visibility = 'hidden';
        changepage.style.height = "0.001px";
        clearall();
    })
    var checkb = document.querySelectorAll('.check_box');

    function clearall() {
        $('.publish-course').innerHTML = '修改发布'
        $('.add-title').value = ''
        $('.add-courseNowPrice').value = ''
        $('.add-teacherName').value = ''
        $('.add-courseOriginPrice').value = ''
        $('.add-teacherBrief').value = ''
        $('.course-brief').value = ''
        for (var i = 0; i < checkb.length; i++) {
            checkb[i].value = '';
        }
    }

    function cleardetail() {
        $('#t1').value = '';
        $('#t2').value = '';
        $('#t3').value = '';
        $('#t4').value = '';
        document.getElementById('tip').innerHTML = '';
    }

    function Changecourse(res) {
        var btn = document.querySelectorAll(".btn");
        for (let o = 0; o < btn.length; o++) {
            btn[o].onclick = function() {
                getChangeInfo(res[o].id);
                changepage.style.visibility = 'visible';
                changepage.style.height = "560px";
            }
        }
    }


    function editdetail(res) {
        var btn6 = document.querySelectorAll(".editbtn");
        var pushdetail = $('.pushdetailbtn');
        for (let o = 0; o < btn6.length; o++) {
            btn6[o].onclick = function() {
                setTimeout(() => {
                    detailpage.style.visibility = 'visible';
                    detailpage.style.height = "660px";
                }, 100)
                detailpage.style.display = 'block';
                detailpage.style.height = "0.01px";
                detailpage.style.visibility = 'hidden';
                pushdetail.addEventListener('click', function() {
                    postdetailCourse(res[o].id);
                })

            }
        }
    }



    function editmodule() {
        var btn7 = document.querySelectorAll(".editbtn1");
        var li1 = document.querySelectorAll(".course-li");
        var uploadcoursename1 = $('.upload-module-course-name');
        var name1 = $('.upload-module-name');
        for (let p = 0; p < btn7.length; p++) {
            btn7[p].onclick = function() {
                setTimeout(() => {
                    detailpage1.style.visibility = 'visible';
                    detailpage1.style.height = "500px";
                }, 100)
                detailpage1.style.display = 'block';
                detailpage1.style.height = "0.01px";
                detailpage1.style.visibility = 'hidden';
                var courseid1 = li1[p].getAttribute('courseid');
                uploadcoursename1.setAttribute('courseid', courseid1);
                name1.setAttribute('num', p);
                window.localStorage.setItem('checkid', courseid1)
                var s = -1;
                Getdetailinfo1(courseid1, s);
                var moduleroom = $('.upload-module-name');
                moduleroom.addEventListener('click', function() {
                    window.localStorage.setItem('num', p);
                    var checknum1 = name1.getAttribute('num');
                    if (checknum1 == window.localStorage.getItem('num')) {
                        var checkid = window.localStorage.getItem('checkid');
                        uploadmodule(checkid);
                    }
                })
            }
        }
    }
    //提交修改后的信息
    function changeBaseCourse(courseid, classifyIds) {
        axios({
            method: 'POST',
            url: '/course/changeBaseCourse',
            data: {
                id: courseid - 0,
                title: $('.add-title').value,
                price: $('.add-courseNowPrice').value,
                teacherName: $('.add-teacherName').value,
                classifyIds: classifyIds,
                originalPrice: $('.add-courseOriginPrice').value,
                teacherTitle: $('.add-teacherBrief').value,
                brief: $('.course-brief').value
            }
        }).then(response => {
            console.log(response.data);
            if (response.data.code == 1) {
                console.log('修改成功');
                successtip();
                $('.aftertips').innerHTML = response.data.msg;
                Getmycourse();
            }
            if (response.data.msg == '参数不合理') {
                $('.aftertips').innerHTML = response.data.msg;
                errtip();
            }
        }).catch(err => {
            console.log(err);
        })
    }
    //提交编辑后的详细信息
    function postdetailCourse(courseid) {
        axios({
            method: 'POST',
            url: '/course/changeDetailCourse',
            data: {
                id: courseid,
                background: $('#t1').value,
                interpretation: $('#t2').value,
                teacher_infomation: $('#t3').value,
                subscription: $('#t4').value
            }
        }).then(response => {
            console.log(response.data);
            if (response.data.code == 1) {
                console.log('添加详情信息成功');
                successtip();
                $('.aftertips').innerHTML = '添加详情成功';
                setTimeout(() => {
                    detailmove();
                }, 1600);
                $('#tip').style.color = '#6723a';
                document.getElementById('tip').innerHTML = '添加详情信息成功';
                // $('.aftertips').innerHTML = '添加详情信息成功';
                // successtip();
            }
            if (response.data.msg == '参数不合理') {
                console.log('添加数据不合理');
                $('#tip').style.color = '#e9af56';
                document.getElementById('tip').innerHTML = '添加数据不合理';
                $('.aftertips').innerHTML = '添加数据不合理';
            }
        }).catch(err => {
            console.log(err);
            $('.aftertips').innerHTML = '添加详情信息失败';
            errtip();
        })
    }


    function successtip() {
        var tips = $('.aftertips');
        var tb = $('.tb');
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#67c23a';
        console.log('成功');
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }

    //  操作失败后的提示信息
    function errtip() {
        var tips = $('.aftertips')
        tips.style.opacity = '1';
        tips.style.top = '60px';
        tips.style.color = '#f02019';
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
    //上传课程模块
    function Addlession() {
        var postlessonname = $('.postlessonname');
        var name3 = $('.upload-module-name');
        var u = name3.getAttribute('num');
        axios({
            method: 'POST',
            url: '/lesson/addLesson',
            data: {
                section_id: window.localStorage.getItem('section_id'),
                lesson_name: postlessonname.value
            }
        }).then(response => {
            console.log(response.data);
            if (response.data.code == 1) {
                successtip();
                $('.aftertips').innerHTML = response.data.msg;
                var moduleflag1 = $('.upload-module-course-name');
                var moduleflag2 = moduleflag1.getAttribute('num1');
                var courseid2 = moduleflag1.getAttribute('courseid');
                Getdetailinfo1(courseid2, moduleflag2);
            } else {
                errtip();
                $('.aftertips').innerHTML = response.data.msg;
            }
        }).catch(err => {
            console.log(err.data);
        })
    }
    //删除课程
    function Deletelesson() {
        var del_lesson1 = document.querySelectorAll('.del-lesson1');
        var lesson1 = document.querySelectorAll('.lesson1');
        for (let j = 0; j < del_lesson1.length; j++) {
            var lesson_id = lesson1[j].getAttribute('lessonid');
            del_lesson1[j].onclick = function() {
                axios({
                    method: 'GET',
                    url: '/lesson/deleteLesson',
                    params: {
                        lesson_id: lesson_id
                    }
                }).then(response => {
                    var res = response.data;
                    console.log(res);
                    successtip();
                    var lessoncontent = $('.edit-content');
                    lessoncontent.innerHTML = '';
                    $('.aftertips').innerHTML = res.msg;
                    lesson1[j].style.display = 'none';
                })
            }
        }
    }

    function getLessonContent(lesson_id) {
        axios({
            method: 'GET',
            url: '/lesson/getLessonContent',
            params: {
                lesson_id: lesson_id
            }
        }).then(response => {
            var res = response.data.data;
            var lessoncontent = $('.edit-content');
            lessoncontent.value = '';
            lessoncontent.value = res.content;
        })
    }


    function Getdetailinfo1(courseid, o) {

        axios({
            method: 'GET',
            url: '/course/detail',
            params: {
                id: courseid
            }
        }).then(response => {
            var res = response.data.data;
            var modulespace = $('.module-name');
            modulespace.innerHTML = '';
            var lessonspace = $('.module-course-name');
            lessonspace.innerHTML = '';
            if (res.courseSectionList.length != 0) {
                window.localStorage.removeItem('section_id');
                window.localStorage.removeItem('lesson_id');
                modulespace.innerHTML = '';
                for (let i = 0; i < res.courseSectionList.length; i++) {
                    let li = document.createElement("li");
                    li.className = 'module1';
                    li.setAttribute('sectionid', res.courseSectionList[i].section_id);
                    li.setAttribute('sectionname', res.courseSectionList[i].section_name);
                    // console.log(str1);
                    li.innerHTML = ` <div class="modulename">模块：${res.courseSectionList[i].section_name}</div>`;
                    modulespace.appendChild(li);
                }
                for (var k in res.courseSectionList[0].lessonList) {
                    let li = document.createElement("li");
                    li.className = 'lesson1';
                    li.setAttribute('lessonid', res.courseSectionList[0].lessonList[k].lesson_id);
                    li.setAttribute('sectionname', res.courseSectionList[0].lessonList[k].lesson_name);
                    li.innerHTML = ` <div class="modulename">课程：${res.courseSectionList[0].lessonList[k].lesson_name}<div class="del-lesson1"></div></div>`;
                    lessonspace.appendChild(li);
                }
                if (o != -1) {
                    if (res.courseSectionList[o].lessonList) {
                        lessonspace.innerHTML = '';
                        for (var k in res.courseSectionList[o].lessonList) {
                            let li = document.createElement("li");
                            li.className = 'lesson1';
                            li.setAttribute('lessonid', res.courseSectionList[o].lessonList[k].lesson_id);
                            li.setAttribute('sectionname', res.courseSectionList[o].lessonList[k].lesson_name);
                            li.innerHTML = ` <div class="modulename">课程：${res.courseSectionList[o].lessonList[k].lesson_name}<div class="del-lesson1"></div></div>`;
                            lessonspace.appendChild(li);
                        }
                    } else {
                        errtip();
                        $('.aftertips').innerHTML = '未添加课程';
                    }
                }
                Btnmath2(res);
            }

        })
    }

    // function Getdetailinfo(courseid, o) {

    //     axios({
    //         method: 'GET',
    //         url: '/course/detail',
    //         params: {
    //             id: courseid
    //         }
    //     }).then(response => {
    //         var res = response.data.data;
    //         console.log(res);
    //         var modulespace = $('.module-name');
    //         modulespace.innerHTML = '';
    //         var lessonspace = $('.module-course-name');
    //         lessonspace.innerHTML = '';
    //         if (res.courseSectionList.length != 0) {
    //             for (let i = 0; i < res.courseSectionList.length; i++) {
    //                 let li = document.createElement("li");
    //                 li.className = 'module1';
    //                 li.setAttribute('sectionid', res.courseSectionList[i].section_id);
    //                 li.setAttribute('sectionname', res.courseSectionList[i].section_name);
    //                 // console.log(str1);
    //                 li.innerHTML = ` <div class="modulename">模块：${res.courseSectionList[i].section_name}</div>`;
    //                 modulespace.appendChild(li);
    //             }
    //             if (res.courseSectionList[o].lessonList) {
    //                 for (var k in res.courseSectionList[o].lessonList) {
    //                     let li = document.createElement("li");
    //                     li.className = 'lesson1';
    //                     li.setAttribute('lessonid', res.courseSectionList[o].lessonList[k].lesson_id);
    //                     li.setAttribute('sectionname', res.courseSectionList[o].lessonList[k].lesson_name);
    //                     li.innerHTML = ` <div class="modulename">课程：${res.courseSectionList[o].lessonList[k].lesson_name}<div class="del-lesson1"></div></div>`;
    //                     lessonspace.appendChild(li);
    //                 }
    //             } else {
    //                 errtip();
    //                 $('.aftertips').innerHTML = '未添加课程';
    //             }
    //             // Changemoduleclass(o);
    //             Btnmath2(res);

    //         }

    //     })
    // }

    // function Changemoduleclass(a) {
    //     var libtn3 = document.querySelectorAll('.module1');
    //     for (let i = 0; i < libtn3.length; i++) {
    //         for (let j = 0; j < libtn3.length; j++) {
    //             libtn3[j].className = "module1";
    //         }
    //         libtn3[a].className = "module1 clickli";
    //     }
    //     Deletelesson();


    // }
    var shan1 = $('.cancel-upload-module-name');
    var shan2 = $('.cancel-upload-module-course-name');
    var nei1 = $('.postmodulename');
    var nei2 = $('.postlessonname');
    shan1.addEventListener('click', function() {
        nei1.value = '';
    })
    shan2.addEventListener('click', function() {
        nei2.value = '';
    })

    function Btnmath2(res1) {
        var postlessonname1 = '';
        var moduleflag = $('.upload-module-course-name');
        var libtn = document.querySelectorAll('.module1');
        var lessonspace = $('.module-course-name');
        var basenum = '';
        for (let i = 0; i < libtn.length; i++) {
            libtn[i].onclick = function() {
                for (let j = 0; j < libtn.length; j++) {
                    libtn[j].className = "module1";
                }
                this.className = "clickli";
                moduleflag.setAttribute('num1', i);
                postlessonname1 = libtn[i].getAttribute('sectionid');
                basenum = i;
                window.localStorage.setItem('section_id', postlessonname1)
                console.log(postlessonname1);
                lessonspace.innerHTML = '';
                for (var k in res1.courseSectionList[i].lessonList) {
                    let li = document.createElement("li");
                    li.className = 'lesson1';
                    li.setAttribute('lessonid', res1.courseSectionList[i].lessonList[k].lesson_id);
                    li.setAttribute('sectionname', res1.courseSectionList[i].lessonList[k].lesson_name);
                    li.innerHTML = ` <div class="modulename">课程：${res1.courseSectionList[i].lessonList[k].lesson_name}<div class="del-lesson1"></div></div>`;
                    lessonspace.appendChild(li);
                }
                Btnmath1();
            }
        }
        moduleflag.addEventListener('click', function() {
            var checknum = moduleflag.getAttribute('num1');
            window.localStorage.setItem('num1', basenum);
            if (checknum == window.localStorage.getItem('num1')) {
                Addlession();
            }
        })
    }

    function Btnmath1() {
        var libtn1 = document.querySelectorAll('.lesson1');
        var save_edit1 = $('.save-edit');
        for (let i = 0; i < libtn1.length; i++) {
            libtn1[i].onclick = function() {
                for (let j = 0; j < libtn1.length; j++) {
                    libtn1[j].className = "lesson1";
                }
                this.className = "clickli1";
                var lesson_id1 = libtn1[i].getAttribute('lessonid');
                console.log(lesson_id1);
                save_edit1.setAttribute('lesson_id', lesson_id1);
                window.localStorage.setItem('lesson_id', lesson_id1);
                getLessonContent(lesson_id1);
            }
        }
        Deletelesson();
        save_edit1.addEventListener('click', function() {
            uploadcontent();
        })


    }

    function uploadcontent() {
        var lessoncontent1 = $('.edit-content');
        var lesson_id1 = window.localStorage.getItem('lesson_id');
        if (lesson_id1 != 0) {
            axios({
                method: 'GET',
                url: '/lesson/editLesson',
                params: {
                    lesson_id: lesson_id1,
                    content: lessoncontent1.value
                }
            }).then(response => {
                var res = response.data;
                lessoncontent1.value = '';
                console.log(res);
                if (res.code == 1) {
                    successtip();
                    $('.aftertips').innerHTML = res.msg;
                    var lesson_id1 = window.localStorage.getItem('lesson_id');
                    getLessonContent(lesson_id1);
                } else {
                    errtip();
                    $('.aftertips').innerHTML = res.msg;
                }
            })
        } else {
            errtip();
            $('.aftertips').innerHTML = '请选择课程！';
        }


    }

    function uploadmodule(courseid) {
        var postmodulename = $('.postmodulename');
        axios({
            method: 'POST',
            url: 'course/addSection',
            data: {
                course_id: courseid,
                section_name: postmodulename.value
            }
        }).then(response => {
            console.log(postmodulename.value);
            var res = response.data;
            console.log(res);
            var name2 = $('.upload-module-name');
            var d = -1;
            Getdetailinfo1(courseid, d);
            successtip();
            $('.aftertips').innerHTML = res.msg;

        })

    }
}